package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.KnowledgeBase;
import com.zja.model.User;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;



/**
 * @author JA
 * @date: 2025/5/3
 * description:新增文章管理员
 */
@WebServlet("/api/knowledgebase/inviteAdmin")
public class InviteKnowledgeBaseAdminServlet extends HttpServlet {
    private final KnowledgeBaseService knowledgeBaseService = new KnowledgeBaseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        Long kbId;
        Long targetUserId;
        try {
            kbId = Long.valueOf(req.getParameter("id"));
            targetUserId = Long.valueOf(req.getParameter("adminId"));
        } catch (NumberFormatException e) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("参数格式错误"));
            return;
        }

        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("未登录，无法邀请用户"));
            return;
        }

        User currentUser = (User) session.getAttribute("currentUser");
        KnowledgeBase kb = knowledgeBaseService.getById(kbId);
        if (kb == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("知识库不存在"));
            return;
        }

        if (!kb.getCreatorId().equals(currentUser.getId())) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("您无权邀请该知识库成员"));
            return;
        }

        if (knowledgeBaseService.isAlreadyAdmin(kbId, targetUserId)) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("该用户已经是文章管理员"));
            return;
        }

        boolean success = knowledgeBaseService.addKnowledgeBaseAdmin(kbId, targetUserId);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("邀请成功"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("邀请失败"));
        }
    }
}
